<template>
<div style="background-color: #EAEAEA;">
  <div>
    <div v-for='(v,i) in sale_cards' :key="i">
      <div class="card" @click="clickCard(v,i)">
        <div :class="{'active':i==select_index}">
          <div class="zan-cell zan-cell--access">
            <div style="width:95%">
              <span style="font-weight:bold;color:#00BF6A;">{{v.card_tpl_name}}</span>
            </div>
            <div style="float:right;">
              <van-icon name="checked" color="#00BF6A" size="20px" v-if="(i==select_index)" />
              <!-- <van-icon name="check" size="20px" v-else/> -->
            </div>
          </div>
          <div class="zan-cell zan-cell--access">
            <span style="font-weight:bold;">余&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;额</span>
            <span style="margin-left:10px;">{{v.origin_price/100}}</span>
          </div>
          <div class="zan-cell zan-cell--access">
            <span style="font-weight:bold;">售&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;价</span>
            <span style="margin-left:10px;">{{v.price/100}}</span>
          </div>
          <div class="zan-cell zan-cell--access" v-if="(v.gifts!=null&&v.gifts.length!=0)">
            <span style="font-weight:bold;">赠&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;送</span>
            <div class="zan-cell__bd" style="float:left;text-align:left;margin-left:10px;">
              <div v-for="item in v.gifts">
                {{item.name}}
              </div>
            </div>
          </div>
          <div class="zan-cell zan-cell--access">
            <span style="font-weight:bold;">截止日期</span>
            <span style="margin-left:10px;"></span>{{v.end_time1}}
          </div>
        </div>
      </div>
    </div>

    <div class="card" style="margin-bottom:65px;overflow: hidden;">
      <div style="padding:10px 15px;font-size:15px;vertical-align: middle;">
        <span style="font-weight:bold;line-height:35px;">手机号</span>
        <span style="margin-left:10px;">{{mobile}}</span>
        <button type="primary" class='btnMobile' open-type="getPhoneNumber"
                            @getphonenumber="getPhoneNumber">获取
                    </button>
      </div>
      <div class="zan-cell zan-cell--access">
        <span style="color:#c0c0c0;">tips：手机号会做为您的会员卡号</span>
      </div>
    </div>

    <div class="operate-bar">
      <div class='gouwuche'>
        <div style="float:left;padding-left:10px;">实付</div>
        <span style="float:bottom;color:#00BF6A;font-size:14px;margin-left:10px;">￥ </span>
        <span style="color:#00BF6A;" v-text="sale_card.price/100"></span>
      </div>

      <div class="submit-btn" @click='pay'>
        <div class="submit-btn-label">确定</div>
      </div>
    </div>

  </div>
</div>
</template>
<script>
import api from '@/utils/api'
import {
  mapGetters
} from 'vuex'

export default {
  data() {
    return {
      select_index: -1,
      sale_cards: [],
      employee_id: 3,
      mobile: '',
      pay_amount: 0,
      sale_card: {
        price: 0
      },
    }
  },
  computed: {
    ...mapGetters([
      'login_info',
      // 'user'
    ])
  },
  onLoad(options) {
    if (options && options.scene) {
      this.login_info.employee_id = options.scene
      this.$store.dispatch('login', this.login_info)
    }
  },
  onUnload(){
    this.sale_cards = []
    this.sale_card={price: 0}
    this.select_index=-1
    this.mobile=''
  },
  beforeMount() {
    // this.pay_amount=0
    if (!this.login_info || !this.login_info.brand_id) {
      // 用户未授权
      let url = 'get_user_info?callback_url=sale_cards'
      wx.redirectTo({
        url: url
      })
      return
    }

  },
  mounted() {
    let self = this
    api.findSaleCards({
      brand_id: this.login_info.brand_id,
      status: 'enable'
    }).then(res => {
      if (res.code == 0) {
        if (res.data.data) {
          res.data.data.forEach(v => {
            v.begin_time1 = self.formatTime(v.begin_time)
            v.end_time1 = self.formatTime(v.end_time)
            self.sale_cards.push(v)
          })
          self.sale_cards = JSON.parse(JSON.stringify(self.sale_cards))
        }
      }
    })
  },

  methods: {
    formatTime(s) {
      var date = new Date(s)
      var array1 = []
      array1.push(date.getFullYear())
      array1.push(date.getMonth() + 1)
      array1.push(date.getDate())

      var array2 = []
      array2.push(date.getHours())
      array2.push(date.getMinutes())
      array2.push(date.getSeconds())

      this.formatArray(array1)
      this.formatArray(array2)

      return array1.join('-') + ' ' + array2.join(':')
    },
    formatArray(array) {
      array.forEach((v, i) => {
        if (v < 10) {
          array[i] = '0' + v
        }
      })
    },

    tab(index) {
      this.num = index;
    },
    handletabContents(arrayCoupons) {
      let coupons = []
      arrayCoupons.forEach(item => {
        item.begin_time = this.formatDate(item.begin_time)
        item.end_time = this.formatDate(item.end_time)
        item.coupon_type = this.handle_coupon_type(item.coupon_type)
        coupons.push(item)
      })
      this.tabContents.push(coupons)
    },
    formatDate(val) {
      const date = new Date(val)
      const year = date.getFullYear()
      const month = date.getMonth() + 1
      const day = date.getDate()
      return year + '-' + month + '-' + day
    },
    clickCard(v, i) {
      this.sale_card = JSON.parse(JSON.stringify(v))
      this.select_index = i
    },
    pay() {
      let self=this
      if (this.mobile == '') {
        wx.showToast({
          title: '请获取手机号',
          icon: 'none'
        })
        return
      }
      if (!this.sale_card||this.sale_card.price < 1) {
        wx.showToast({
          title: '请选择会员卡',
          icon: 'none'
        })
        return
      }

      let form = {
        sale_card_id: this.sale_card.id,
        employee_id: this.login_info.employee_id,
        user_card_no: this.mobile,
        user_open_id: this.login_info.openid,
      }

      api.paySaleCardRecord(form).then(res => {
        if (res.code == 0) {
          wx.requestPayment({
            'timeStamp': res.data.timeStamp,
            'nonceStr': res.data.nonceStr,
            'package': res.data.package,
            'signType': res.data.signType,
            'paySign': res.data.paySign,
            success(result) {
              wx.showToast({
                title: '支付成功',
                icon: 'success'
              })
              self.$store.dispatch('refreshUser')
              wx.switchTab({url:'index'})
            },
            fail(result) {
              console.log('支付失败：', result)
            }
          })

        } else {
          this.showToast(res.msg)
        }
      })
    },
    getPhoneNumber(e) {
      console.log(e)
      if (e.target.errMsg == "getPhoneNumber:fail user deny") {
        this.showToast('请点击允许')
        return
      }
      // this.form.phone="123"

      let self = this
      api.wechatDecryptPhoneData({
        iv: e.target.iv,
        session_key: this.login_info.session_key,
        encrypted_data: e.target.encryptedData
      }).then(result => {
        if (result.code === 0) {
          this.mobile = result.data.phoneNumber
        }
      })
    },
    showToast(msg){
      wx.showToast({title:msg,icon:'none'})
    }
  }
}
</script>

<style>
page {
  background: #EAEAEA;
}

.tab-h {
  width: 100%;
  display: flex;
  flex-direction: row;
  line-height: 40px;
  height: 40px;
  font-size: 20px;
  background: white;
}

.tab-item {
  width: 33%;
  display: inline-block;
  text-align: center;
}

.tab-item.active {
  position: relative;
}

.tab-item.active:after {
  content: "";
  display: block;
  height: 4px;
  width: 60px;
  background: #4F4F4F;
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translate(-50%);
  border-radius: 1px;
}

.card {
  width: 90%;
  margin: 10px auto;
  background: white;
  border-radius: 5px;
}

.card .active {
  /* background: red; */
  border: 2px solid #00BF6A;
  border-radius: 5px;
  /* text-align: center; */
}

.btnMobile {
  border: solid 1px #EAEAEA;
  border-radius: 3px;
  float: right;
  text-align: center;
  line-height: 35px;
}

.operate-bar {
  z-index: 1001;
  position: fixed;
  bottom: 0px;
  height: 55px;
  line-height: 55px;
  width: 100%;
  display: flex;
}

.gouwuche {
  width: 70%;
  background: white;
  height: 100%;
}

.submit-btn {
  height: 100%;
  background-color: #00BF6A;
  width: 30%;
  display: flex;
}

.submit-btn-label {
  color: white;
  font-size: 20px;
  margin: auto;
}
</style>
